package com.lucky.ebidding.service;

import com.lucky.ebidding.dao.ExpertDao;
import com.lucky.ebidding.dao.UserDao;
import com.lucky.ebidding.model.Expert;
import com.lucky.ebidding.model.ExpertExample;
import com.lucky.ebidding.model.User;
import com.lucky.ebidding.model.UserShInfo;
import com.lucky.ebidding.service.interfaces.ExpertServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * ClassName:ExpertService
 * Package:com.lucky.ebidding.service
 * Description:
 *
 * @Date:2020/5/13 17:24
 * @Author:857251389@qq.com
 */
@Service
public class ExpertService implements ExpertServiceI {

    @Autowired
    private ExpertDao expertDao;

    @Autowired
    private NotificationService notificationService;
    @Override
    public Expert selectByUserId(Integer userId) {

        ExpertExample expertExample = new ExpertExample();
        expertExample.createCriteria().andUserIdEqualTo(userId);
        List<Expert> experts = expertDao.selectByExample(expertExample);
        return experts.get(0);
    }

    @Override
    public void insertAdd(Expert expert) {

        expertDao.updateByPrimaryKeySelective(expert);
    }

    @Override
    public List<Expert> selectAllExpert() {

        List<Expert> experts = expertDao.selectByExample(new ExpertExample());

        return experts;
    }

    @Override
    public int setStatus(Integer id, Integer status,User user) {
        Expert expert = new Expert();
        expert.setId(id);
        expert.setShFlag(status);
        int i = expertDao.updateByPrimaryKeySelective(expert);
        Expert expert1 = expertDao.selectByPrimaryKey(id);
        if(status == 1){
            notificationService.sendShNotification(expert1.getUserId(),user.getId(),3,"通过");
        }else if(status == 2){
            notificationService.sendShNotification(expert1.getUserId(),user.getId(),3,"未通过，请重新上传审核文件");
        }
        return i;
    }

    @Override
    public List<Expert> selectExpert(Integer number,Integer type,Integer zbId, User user) {

        ExpertExample expertExample = new ExpertExample();
        expertExample.createCriteria().andTypeEqualTo(type);
        List<Expert> experts = expertDao.selectByExample(expertExample);
        ArrayList<Expert> expertList = new ArrayList<>();
        for (int i = 0;i<number;i++){
            Random random = new Random();
            int randomExpertIndex = random.nextInt(experts.size());
            Expert expert = experts.get(randomExpertIndex);
            //给专家发送通知
            notificationService.sendNotification(expert.getUserId(),user.getId(),1,zbId,"邀请您参与");
            experts.remove(randomExpertIndex);
            expertList.add(expert);
        }

        return expertList;
    }
}
